﻿using System;
using System.Collections;
using System.Diagnostics;
using ProjectDanmaku.Core;
using ProjectDanmaku.Entity.SubLayer.EnemyBullet;
using ProjectDanmaku.Util;
using UnityEngine;
using Debug = UnityEngine.Debug;
using Random = System.Random;

namespace ProjectDanmaku.Enemy.Boss.Nightbug
{
    public class BossNightbugCreation0 : ShootableObject
    {
        private Random _random = new ();

        [SerializeField] private int explodeBulletCount;
        [SerializeField] private GameObject explodeSoundPrefab;
        
        [HideInInspector] public SimpleBulletSubLayer bulletLayer;

        private Animator _animator;
        
        private int hp = 5;
        private bool dead = false;

        private void Awake()
        {
            _animator = GetComponent<Animator>();
        }

        private void Start()
        {
            StartCoroutine(MainCoroutine());
        }

        private IEnumerator MainCoroutine()
        {
            yield return new WaitForSeconds(1f + _random.Next(0, 5) / 10f);

            if (dead)
                yield break;
            
            var pos = transform.position;
            var posV2 = new Vector2(pos.x, pos.y);
            
            for (int i = 0; i < explodeBulletCount; i++)
            {
                bulletLayer.Shoot(
                    posV2 + new Vector2(_random.Next(-10, 10) / 1000f, _random.Next(-10, 10) / 1000f),
                    1, _random.Next(0, 360));
            }
            
            PrepareDestroy(true);
        }
        
        public override void OnShot()
        {
            if (--hp <= 0)
            {
                dead = true;
                PrepareDestroy(true);
            }
        }

        public void PrepareDestroy(bool playSound = false)
        {
            dead = true;
            _animator.SetTrigger("Death");
            RemoveSelfFromShootableObjects();
            Destroy(gameObject, 1f);

            if (playSound)
                Instantiate(explodeSoundPrefab);
        }

        public override CircleCollider GetCollider()
        {
            return ColliderFromPosition(CoordUtility.PixelToUnit(27));
        }

        protected override int GetLayer()
        {
            return 2;
        }
    }
}